package com.okq.action;

import com.okq.action.base.BaseActionSupport;
import com.okq.entity.*;
import com.okq.service.*;
import com.okq.util.BaseTool;
import com.okq.util.PublicClass;
import com.okq.util.TimeTool;
import com.okq.util.page.Page;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.PrintWriter;
import java.util.*;

/**
 * 描述 : 客户action
 * 作者 : zdl
 * 日期 : 2017/7/13 9:34
 */
public class CustomerAction extends BaseActionSupport {
    private static final long serialVersionUID = 8532809060676427081L;
    /**
     * 客户接口
     */
    @Autowired
    private ICustomerService customerServiceImpl;
    /**
     * 公司接口
     */
    @Autowired
    private ICompanyService companyServiceImpl;
    /**
     * 角色接口
     */
    @Autowired
    private IRoleService roleServiceImpl;
    /**
     * 用户接口
     */
    @Autowired
    private IUserService userServiceImpl;

    /**
     * 系统日志接口
     */
    @Autowired
    private ILogService logServiceImpl;
    /**
     * 日志
     */
    private static final Logger logger = Logger.getLogger(CustomerAction.class);
    /**
     * 分页开始条数
     */
    private int iDisplayStart;

    /**
     * 每页显示条数
     */
    private int iDisplayLength;

    private String id;
    private String type;
    private Customer customer;
    private String levelStr ;
    private String chargeName;//返回销售负责人
    private String ids;// 选中客户id字符串

    /**
     * 获取客户分页列表
     * @return json
     */
    public String getCustomerList() {
        PrintWriter out = null;
        try {
            out = this.getResponse().getWriter();
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null) {
                if (iDisplayLength == 0) {
                    iDisplayLength = -1;
                }
                int pageNum = (int) (Math.ceil(iDisplayStart / iDisplayLength)) + 1;
                /* 分页信息 */
                Page<Customer> pageInfo = new Page<>(iDisplayLength);
                pageInfo.setPageNo(pageNum);
                pageInfo = customerServiceImpl.pageByCustomer(pageInfo, customer);
                int iTotalRecords = pageInfo.getTotalCount();
                int iTotalDisplayRecords = pageInfo.getTotalCount() < 0 ? 0 : pageInfo.getTotalCount();
                /* 得到结果 */
                List<Customer> cList = pageInfo.getResult();
                /* 封装list */
                List<Map<String, Object>> cMapList = new ArrayList<>();
                if (cList != null && !cList.isEmpty() && cList.size() > 0) {
                    int i = (pageNum - 1) * iDisplayLength + 1;
                    for (Customer c : cList) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("no", i);// 序号
                        map.put("id", c.getId());
                        map.put("name", StringUtils.defaultString(c.getName(), ""));
                        map.put("contact", StringUtils.defaultString(c.getContact(), ""));
                        map.put("email", StringUtils.defaultString(c.getEmail(), ""));
                        map.put("address", StringUtils.defaultString(c.getAddress(), ""));
                        String customerLevel;
                        Integer level = c.getLevel();
                        if (level == 1) {
                            customerLevel = "会员";
                        } else {
                            customerLevel = "普通";
                        }
                        map.put("customerLevel", customerLevel);
                        map.put("remark", StringUtils.defaultString(c.getRemark(), ""));
                        String chargeId = c.getChargeId();
                        String chargeName = "";
                        if (StringUtils.isNotBlank(chargeId)) {
                            User u = userServiceImpl.getUserById(chargeId);
                            if (u != null) {
                                chargeName = StringUtils.defaultString(u.getUserName(), "");
                            }
                        }
                        map.put("chargeName", chargeName);
                        map.put("createTime", TimeTool.timestampToString(c.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
                        cMapList.add(map);
                        i++;
                    }
                }
                Map<String, Object> jsonMap = new HashMap<>();
                jsonMap.put("iTotalRecords", iTotalRecords);
                jsonMap.put("iTotalDisplayRecords", iTotalDisplayRecords);
                jsonMap.put("aaData", cMapList);

                String json = BaseTool.toJson(jsonMap);
                out.print(json);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }

    /**
     * 删除
     *
     * @return 成功标识
     */
    public String deleteCustomer() {
        PrintWriter out = null;
        try {
            out = this.getResponse().getWriter();
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null && StringUtils.isNotBlank(id)) {
                Customer c = customerServiceImpl.getCustomerById(id);
                if (c != null) {
                    c.setIsDelete(1);
                    c.setUpdateUserId(loginUser.getId());
                    c.setUpdateUserName(loginUser.getUserName());
                    customerServiceImpl.updateCustomer(c);
                    out.print(0);
                    //添加系统日志
                    String userName = loginUser.getUserName();
                    String nowTime = TimeTool.getNowTime();
                    String content = "用户：" + userName + "，于" + nowTime + " 删除客户：" + c.getName() + "！";
                    PublicClass.addLog(userName, loginUser.getLoginName(), "客户管理", 2, content, logServiceImpl);
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }

    /**
     * 跳转到修改或详情页面
     *
     * @return 标识
     */
    @SuppressWarnings("all")
    public String toUpdateOrDetail() {
        try {
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null && StringUtils.isNotBlank(id)) {
                customer = customerServiceImpl.getCustomerById(id);
                if (customer != null) {
                    Integer level = customer.getLevel();
                    if (level == 1) {
                        levelStr = "会员";
                    } else {
                        levelStr = "普通";
                    }
                    String chargeId = customer.getChargeId();
                    if (StringUtils.isNotBlank(chargeId)) {
                        User u = userServiceImpl.getUserById(chargeId);
                        if (u != null) {
                            chargeName = StringUtils.defaultString(u.getUserName(), "");
                        }
                    }
                    if (type.equals("update")) {
                        return "update";
                    } else if (type.equals("detail")) {
                        return "detail";
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
        return null;
    }

    /**
     * 保存
     *
     * @return 成功标识
     */
    public String saveCustomer() {
        PrintWriter out = null;
        try {
            out = this.getResponse().getWriter();
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null && customer != null) {
                String userName = loginUser.getUserName();
                if (StringUtils.isNotBlank(type) && type.equals("add")) {// 新增
                    String contact = customer.getContact();
                    if (StringUtils.isNotBlank(contact)) {
                        Customer c = customerServiceImpl.getCustomerByContact(contact);
                        if (c != null) {
                            out.print("exist");
                            return null;
                        }
                    }
                    customer.setId(BaseTool.getPK());
                    if (StringUtils.isNotBlank(userName)) {
                        customer.setCreateUserId(loginUser.getId());
                        customer.setCreateUserName(userName);
                    }
                    String comCode = loginUser.getComCode();
                    if (StringUtils.isNotBlank(comCode)) {
                        customer.setComCode(comCode);
                    }
                    customerServiceImpl.saveCustomer(customer);
                    out.print("success");
                    //添加系统日志
                    String nowTime = TimeTool.getNowTime();
                    String content = "用户：" + userName + "，于" + nowTime + " 添加客户：" + customer.getName() + "！";
                    PublicClass.addLog(userName, loginUser.getLoginName(), "客户管理", 2, content, logServiceImpl);
                } else if (StringUtils.isNotBlank(type) && type.equals("update")) {// 修改
                    Customer oldCustomer = customerServiceImpl.getCustomerById(customer.getId());
                    if (oldCustomer != null) {
                        String oldContact = oldCustomer.getContact();
                        String newContact = customer.getContact();
                        if (!newContact.equals(oldContact)) {
                            Customer c = customerServiceImpl.getCustomerByContact(newContact);
                            if (c != null) {
                                out.print("exist");
                                return null;
                            }
                        }
                        oldCustomer.setName(customer.getName());
                        oldCustomer.setContact(newContact);
                        oldCustomer.setEmail(customer.getEmail());
                        oldCustomer.setAddress(customer.getAddress());
                        Integer level = customer.getLevel();
                        if (level != null && level != -1) {
                            oldCustomer.setLevel(level);
                        }
                        oldCustomer.setChargeId(customer.getChargeId());
                        oldCustomer.setRemark(customer.getRemark());
                        if (StringUtils.isNotBlank(userName)) {
                            oldCustomer.setUpdateUserId(loginUser.getId());
                            oldCustomer.setUpdateUserName(userName);
                        }
                        customerServiceImpl.updateCustomer(oldCustomer);
                        out.print("success");
                        //添加系统日志
                        String nowTime = TimeTool.getNowTime();
                        String content = "用户：" + userName + "，于" + nowTime + " 修改客户：" + customer.getName() + "！";
                        PublicClass.addLog(userName, loginUser.getLoginName(), "客户管理", 2, content, logServiceImpl);
                    }

                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }

    /**
     * 选择客户
     *
     * @return 客户树节点
     */
    @SuppressWarnings("all")
    public String selectCustomer() {
        PrintWriter out = null;
        try {
            out = this.getResponse().getWriter();
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null) {
                List<TreeNode> treeNodes = new ArrayList<>();
                String loginRoleId = loginUser.getRoleId();
                if (StringUtils.isNotBlank(loginRoleId)) {
                    Role role = roleServiceImpl.getRoleById(loginRoleId);
                    if (role != null) {
                        Integer roleType = role.getRoleType();
                        if (roleType == 0) {// 超级管理员能查询所有公司下所有客户
                            List<Company> cList = companyServiceImpl.listAllCompany();
                            if (cList != null && !cList.isEmpty() && cList.size() > 0) {
                                for (Company c : cList) {
                                    TreeNode ct = new TreeNode();
                                    ct.setId("cid_" + c.getId());
                                    ct.setName(c.getName());
                                    ct.setpId("cid_0");
                                    ct.setParent(true);
                                    treeNodes.add(ct);
                                }
                                List<Customer> cusList = customerServiceImpl.listAllCustomer();
                                if (cusList != null && !cusList.isEmpty() && cusList.size() > 0) {
                                    for (Customer cus : cusList) {
                                        String comCode = cus.getComCode();
                                        if (StringUtils.isNotBlank(comCode)) {
                                            Company company = companyServiceImpl.getCompanyByComCode(comCode);
                                            if (company != null) {
                                                TreeNode gt = new TreeNode();
                                                gt.setId("cusid_" + cus.getId());
                                                gt.setName(cus.getName());
                                                gt.setpId("cid_" + company.getId());
                                                treeNodes.add(gt);
                                            }
                                        }
                                    }
                                }
                            }
                        } else {// 管理员能看到自己所属公司下所有客户
                            String comCode = loginUser.getComCode();
                            if (StringUtils.isNotBlank(comCode)) {
                                List<Customer> cusList = customerServiceImpl.listCustomerByComCode(comCode);
                                if (cusList != null && !cusList.isEmpty() && cusList.size() > 0) {
                                    for (Customer cus : cusList) {
                                        Company company = companyServiceImpl.getCompanyByComCode(comCode);
                                        if (company != null) {
                                            TreeNode gt = new TreeNode();
                                            gt.setId("cusid_" + cus.getId());
                                            gt.setName(cus.getName());
                                            gt.setpId("cid_" + company.getId());
                                            treeNodes.add(gt);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                String json = BaseTool.toJson(treeNodes);
                out.print(json);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }

    /**
     * 获取选中客户名称
     *
     * @return name
     */
    public String getCustomerName() {
        PrintWriter out = null;
        try {
            out = this.getResponse().getWriter();
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null && StringUtils.isNotBlank(ids)) {
                String customerName = "";
                String[] idsArr = ids.split(",");
                if (idsArr.length > 0) {
                    for (String customerId : idsArr) {
                        Customer cus = customerServiceImpl.getCustomerById(customerId);
                        if (cus != null) {
                            customerName = StringUtils.defaultString(cus.getName(), "");
                        }
                    }
                    out.print(customerName);
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }

    public int getIDisplayStart() {
        return iDisplayStart;
    }

    public void setIDisplayStart(int iDisplayStart) {
        this.iDisplayStart = iDisplayStart;
    }

    public int getIDisplayLength() {
        return iDisplayLength;
    }

    public void setIDisplayLength(int iDisplayLength) {
        this.iDisplayLength = iDisplayLength;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getLevelStr() {
        return levelStr;
    }

    public void setLevelStr(String levelStr) {
        this.levelStr = levelStr;
    }

    public String getChargeName() {
        return chargeName;
    }

    public void setChargeName(String chargeName) {
        this.chargeName = chargeName;
    }

    public String getIds() {
        return ids;
    }

    public void setIds(String ids) {
        this.ids = ids;
    }
}
